#include "chatclient.h"
#include "ui_chatclient.h"
#include "QStringBuilder"
#include "QMessageBox"

ChatClient::ChatClient(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChatClient)
{
    ui->setupUi(this);
    m_isCloseSystem = false;

    m_msgSocket = new MsgSocket(this);   
    m_subLogin = new SubLogin;
    m_subLogin->show();
    m_privateFormMap.clear();

    connect(m_subLogin, SIGNAL(signalUserRegiter(UserInfo)),
            this, SLOT(slotUserRegister(UserInfo)));
    connect(m_msgSocket, SIGNAL(signalUserRegisterResult(bool)),
            this, SLOT(slotUserRegisterResult(bool)));
    connect(m_subLogin, SIGNAL(signalUserLogin(QString, QString)),
            this, SLOT(slotUserLogin(QString, QString)));
    connect(m_msgSocket, SIGNAL(signalUserLoginResult(bool, QString)),
            this, SLOT(slotUserLoginResult(bool, QString)));
    connect(m_msgSocket, SIGNAL(signalUserLogoutResult(bool)),
            this, SLOT(slotUserLogoutResult(bool)));

    connect(m_msgSocket, SIGNAL(signalGetOnlineUserResult(bool)),
            this, SLOT(slotGetOnlineUserResult(bool)));
    connect(m_msgSocket, SIGNAL(signalGetMsgAllResult(QString)),
            this, SLOT(slotGetMsgAllResult(QString)));

    connect(m_msgSocket, SIGNAL(signalGetMsgPrivateResult(QString, QString)),
            this, SLOT(slotGetMsgPrivateResult(QString, QString)));
}

ChatClient::~ChatClient()
{
    delete ui;
}

void ChatClient::initForm()
{
    ui->lb_id->setText(GlobalVars::g_localUser.getID());
    ui->lb_name->setText(GlobalVars::g_localUser.getName());

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(2);

    QStringList header;
    header << "账号" << "名字";
    ui->tableWidget->setHorizontalHeaderLabels(header);
    ui->tableWidget->verticalHeader()->setVisible(false);
    ui->tableWidget->setRowCount(GlobalVars::g_onlineUserList->length() - 1);
    for(int i = 0, j = 0; i < GlobalVars::g_onlineUserList->length(); i++)
    {
        if (GlobalVars::g_onlineUserList->at(i).getID() != GlobalVars::g_localUser.getID())
        {
            QTableWidgetItem *item = new  QTableWidgetItem(GlobalVars::g_onlineUserList->at(i).getID());
            ui->tableWidget->setItem(j, 0, item);
            item = new  QTableWidgetItem(GlobalVars::g_onlineUserList->at(i).getName());
            ui->tableWidget->setItem(j, 1, item);
            j++;
        }
    }
}

/////////////////////////////////////注册///////////////////////////////////
void ChatClient::slotUserRegister(UserInfo info)
{
    qDebug() << "ChatClient::slotUserRegister";
    QString msg = QString("R")
            % QString("|") % info.getID()
            % QString("|") % info.getName()
            % QString("|") % info.getPswd();

    m_msgSocket->slotSendMessage(msg);
}

void ChatClient::slotUserRegisterResult(bool res)
{
    qDebug() << "ChatClient::slotUserRegisterResult";
    if (res)
    {
        QMessageBox msgBox;
        msgBox.setStyleSheet("background-color: rgb(255, 255, 42);");
        msgBox.setText("注册成功");
        msgBox.setInformativeText("请返回登录！");
        msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Yes);
        msgBox.setDefaultButton(QMessageBox::Retry);
        int res = msgBox.exec();
        switch (res) {
        case QMessageBox::Yes: m_subLogin->registerSuccess(); break;
        default:
            break;
        }
    }else
    {
        QMessageBox msgBox;
        msgBox.setStyleSheet("background-color: rgb(255, 255, 42);");
        msgBox.setText("注册失败");
        msgBox.setInformativeText("账号已有，不可用！");
        msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close);
        msgBox.setDefaultButton(QMessageBox::Retry);
        res = msgBox.exec();
    }
}

/////////////////////////////////////登录///////////////////////////////////
void ChatClient::slotUserLogin(QString id, QString pswd)
{
    qDebug() << "void ChatClient::slotUserLogin";
    QString msg = QString("L") % QString("|") % id % QString("|") % pswd;

    m_msgSocket->slotSendMessage(msg);
}

void ChatClient::slotUserLoginResult(bool res, QString msg)
{
    qDebug() << "ChatClient::slotUserLoginResult";
    if (res)
    {
        m_subLogin->hide();
        this->show();
        initForm();
        slotGetOnlineUser();
    }else
    {
        if (msg == "1")
        {
            QMessageBox msgBox;
            msgBox.setStyleSheet("background-color: rgb(255, 255, 42);");
            msgBox.setText("登录失败!");
            msgBox.setInformativeText("请不要重复登录!");
            msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close);
            msgBox.setDefaultButton(QMessageBox::Retry);
            msgBox.exec();
        }else
        {
            QMessageBox msgBox;
            msgBox.setStyleSheet("background-color: rgb(255, 255, 42);");
            msgBox.setText("登录失败!");
            msgBox.setInformativeText("用户名或者密码错误，请重新输入!");
            msgBox.setStandardButtons(QMessageBox::Retry | QMessageBox::Close);
            msgBox.setDefaultButton(QMessageBox::Retry);
            msgBox.exec();
        }

    }
}

//////////////////////////////////关闭///////////////////////////////////////////
void ChatClient::slotUserLogout()
{
    qDebug() << "ChatClient::slotUserLogout()";
    QString msg = QString("C") % QString("|")
            % GlobalVars::g_localUser.getID();

    m_msgSocket->slotSendMessage(msg);
}

void ChatClient::slotUserLogoutResult(bool res)
{
    qDebug() << "ChatClient::slotUserLogoutResult";
    if (res)
    {
        m_isCloseSystem = true;
        this->close();
    }else
    {
        m_isCloseSystem = false;
    }
}

void ChatClient::closeEvent(QCloseEvent *ev)
{
    if(!m_isCloseSystem)
    {
        slotUserLogout();
        ev->ignore();
    }else
    {
        ev->accept();
    }
}

//////////////////////////////////////获取在线用户/////////////////////////
void ChatClient::slotGetOnlineUser()
{
    qDebug() << "ChatClient::slotGetOnlineUser()";

    QString msg = QString("O")
            % QString("|") % GlobalVars::g_localUser.getID();

    m_msgSocket->slotSendMessage(msg);
}

void ChatClient::slotGetOnlineUserResult(bool res)
{
    qDebug() << "ChatClient::slotGetOnlineUserResult";
    if (res)
    {
        initForm();
    }
}

void ChatClient::on_pushButton_clicked()
{
    QString msg = GlobalVars::g_localUser.getName()
            % QString(" ") % QString("says: ")
            % ui->textEdit->toPlainText();

    QTextCursor tc = ui->textBrowser->textCursor();
    QTextCharFormat tcf = QTextCharFormat();
    tcf.setFontFamily("隶属");
    tcf.setFontPointSize(20);
    tc.insertText(msg,tcf);
    ui->textBrowser->append("\n");

    //ui->textBrowser->append(msg);
    slotSendMsgAll();
    ui->textEdit->clear();
}

void ChatClient::slotSendMsgAll()
{
    QString textmsg = GlobalVars::g_localUser.getName()
            % QString(" ") % QString("says: ")
            % ui->textEdit->toPlainText();

    QString msg = QString("A") % QString("|")
            % GlobalVars::g_localUser.getID()
            % QString("|") % textmsg;

    m_msgSocket->slotSendMessage(msg);
}

void ChatClient::slotGetMsgAllResult(QString msg)
{
    QTextCursor tc = ui->textBrowser->textCursor();
    QTextCharFormat tcf = QTextCharFormat();
    tcf.setFontFamily("隶属");
    tcf.setFontPointSize(20);
    tc.insertText(msg,tcf);
    ui->textBrowser->append("\n");
}

void ChatClient::on_tableWidget_clicked(const QModelIndex &index)
{
    QString id = ui->tableWidget->item(index.row(), index.column())->text();
    QString str = ui->tableWidget->item(index.row(), index.column()+1)->text();

    PrivateForm *privateForm = new PrivateForm;
    connect(privateForm, SIGNAL(signalSendMsgPrivate(QString,QString)),
            this, SLOT(slotSendMsgPrivate(QString,QString)));
    connect(privateForm, SIGNAL(signalPrivateFormClose(QString)),
            this, SLOT(slotPrivateFormClose(QString)));

    privateForm->show();
    privateForm->initForm(id, str);
    m_privateFormMap.insert(id, privateForm);
}

void ChatClient::slotSendMsgPrivate(QString id, QString msg)
{
    qDebug() << "ChatClient::slotSendMsgPrivate";

    QString msg1 = QString("P")
            % QString("|") % GlobalVars::g_localUser.getID()
            % QString("|") % id % QString("|") % msg;

    m_msgSocket->slotSendMessage(msg1);
}

void ChatClient::slotGetMsgPrivateResult(QString id, QString msg)
{
    qDebug() << "ChatClient::slotGetMsgPrivateResult";
    QString name;
    for (UserInfoList::iterator it = GlobalVars::g_onlineUserList->begin();
         it != GlobalVars::g_onlineUserList->end(); it++)
    {
        if (it->getID() == id)
        {
            name = it->getName();
        }
    }

    if (m_privateFormMap.contains(id))
    {
        m_privateFormMap[id]->GetMsgPrivateForm(msg);
    }else
    {
        PrivateForm *privateForm = new PrivateForm;
        connect(privateForm, SIGNAL(signalSendMsgPrivate(QString,QString)),
                this, SLOT(slotSendMsgPrivate(QString,QString)));
        connect(privateForm, SIGNAL(signalPrivateFormClose(QString)),
                this, SLOT(slotPrivateFormClose(QString)));

        privateForm->show();
        privateForm->initForm(id, name);
        privateForm->GetMsgPrivateForm(msg);
        m_privateFormMap.insert(id, privateForm);
    }
}

void ChatClient::slotPrivateFormClose(QString id)
{
    m_privateFormMap.remove(id);
}
